package com.gzyj.jtt808.v2011;

import com.gzyj.jtt808.utils.HexBytesUtil;
import com.gzyj.jtt808.v2011.enums.BusinessDataType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;


/**
 * @author lhj
 */

public class IPackageDecodeAdapter implements PackageDecodeAdapter {
    private Package aPackage;

    @Override
    public Package decode(ByteBuf in) {
        String hex = ByteBufUtil.hexDump(in);
        String tt=hex.substring(hex.indexOf("7e") + 2, hex.lastIndexOf("7e"));

        in = HexBytesUtil.readZy(tt);//转义处理

        byte[] temp = HexBytesUtil.readByOffset(in, 1);
        int startFlag = Integer.parseInt(HexBytesUtil.bytesToHex(temp), 16);

        temp = HexBytesUtil.readByOffset(in, 2);//长度
        BusinessDataType businessType = BusinessDataType.find(Integer.parseInt(HexBytesUtil.bytesToHex(temp), 16));

        try {
            this.aPackage = (Package) Class.forName(businessType.getClazz()).newInstance();
            this.aPackage.decode(Unpooled.copiedBuffer(HexBytesUtil.hexTobytes(hex)));

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        return this.aPackage;
    }
}
